import javax.swing.tree.TreeNode;
import java.util.*;

public class BinaryTree {

    //使用内部类创建节点对象
    static class TreeNode {
        public char val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(char val) {
            this.val = val;
        }
    }

    //创建二叉树
    public TreeNode createTree() {

        //实例化节点对象
        TreeNode A = new TreeNode('A');
        TreeNode B = new TreeNode('B');
        TreeNode C = new TreeNode('C');
        TreeNode D = new TreeNode('D');
        TreeNode E = new TreeNode('E');
        TreeNode F = new TreeNode('F');
        TreeNode G = new TreeNode('G');
        TreeNode H = new TreeNode('H');

        A.left = B;
        A.right = C;
        B.left = D;
        B.right = E;
        E.right = H;
        C.left = F;
        C.right = G;

        //返回二叉树的根节点
        return A;
    }

    //根据所给的先序遍历的字符串创建一个二叉树，并输出它的中序遍历
    public static int i = 0;

    public static TreeNode createTree(String str) {
        TreeNode root = null;
        if (str.charAt(i) != '#') {
            root = new TreeNode(str.charAt(i));
            i++;
            root.left = createTree(str);
            root.right = createTree(str);
        } else {
            i++;
        }
        return root;
    }

    //前序遍历
    public void preOrder(TreeNode root) {
        if (root == null) return;

        System.out.print(root.val + " ");

        preOrder(root.left);
        preOrder(root.right);
    }

    //中序遍历
    public void inOrder(TreeNode root) {
        if (root == null) return;

        inOrder(root.left);

        System.out.print(root.val + " ");

        inOrder(root.right);
    }

    //后序遍历
    public void postOrder(TreeNode root) {
        if (root == null) return;

        postOrder(root.left);
        postOrder(root.right);

        System.out.print(root.val + " ");
    }

    public int nodeSize;

    /**
     * 获取当前二叉树的节点个数
     *
     * @param root
     * @return
     */
    public void getNodeSize(TreeNode root) {
        if (root == null) return;

        nodeSize++;

        getNodeSize(root.left);
        getNodeSize(root.right);
    }

    //子问题思路
    public int getNodeSize2(TreeNode root) {
        if (root == null) return 0;

        //左树的节点加上右树的节点加1
        return getNodeSize2(root.left) + getNodeSize2(root.right) + 1;
    }

    public int leafCount;

    /**
     * 获取该二叉树叶子节点的个数 —— 遍历思路
     *
     * @param root
     */
    public void getLeafCount(TreeNode root) {
        if (root == null) return;

        if (root.left == null && root.right == null) {
            leafCount++;
        }

        getLeafCount(root.left);
        getLeafCount(root.right);
    }

    /**
     * 获取该二叉树叶子节点的个数 —— 子问题思路
     *
     * @param root
     */
    public int getLeafCount2(TreeNode root) {
        if (root == null) return 0;

        if (root.left == null && root.right == null) {
            return 1;
        }

        return getLeafCount2(root.left) + getLeafCount2(root.right);
    }

    /**
     * 获取二叉树第K层的节点数
     *
     * @param root
     * @return
     */
    public int getKLevelNodeCount(TreeNode root, int k) {
        if (root == null) {
            return 0;
        }

        if (k == 1) {
            return 1;
        }

        return getKLevelNodeCount(root.left, k - 1)
                + getKLevelNodeCount(root.right, k - 1);
    }

    /**
     * 求二叉树的高度
     * 时间复杂度为O(n)
     *
     * @param root
     * @return
     */
    public int getHeight(TreeNode root) {
        if (root == null) return 0;

        int leftHeight = getHeight(root.left);
        int rightHeight = getHeight(root.right);

        //return Math.max(leftHeight, rightHeight) + 1;
        return leftHeight > rightHeight ? leftHeight + 1 : rightHeight + 1;
    }

    /**
     * 寻找二叉树的节点值
     *
     * @param root
     * @param key
     * @return
     */
    public TreeNode find(TreeNode root, int key) {
        if (root == null) return null;

        if (root.val == key) {
            return root;
        }

        TreeNode leftResult = find(root.left, key);
        if (leftResult != null) {
            return leftResult;
        }

        TreeNode rightResult = find(root.right, key);
        if (rightResult != null) {
            return rightResult;
        }

        return null;
    }

    /**
     * 判断两棵二叉树是否相同
     * 时间复杂度：p -> m, q -> n, O(min(m, n))
     *
     * @param p
     * @param q
     * @return
     */
    public boolean isSameTree(TreeNode p, TreeNode q) {
        //1.结构上：一个为空，一个不为空
        if ((p == null && q != null) || (p != null && q == null)) {
            return false;
        }

        //2。此时：都不为空或者都为空
        if (p == null && q == null) {
            return true;
        }

        if (p.val != q.val) {
            return false;
        }

        //3.此时：p != null && q != null && p.val == q.val
        return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
    }

    /**
     * 判断一棵二叉树是否是另一棵二叉树的子树
     *
     * @param root
     * @param subRoot
     * @return
     */
    public boolean isSubtree(TreeNode root, TreeNode subRoot) {
        if (root == null) {
            return false;
        }

        if (isSameTree(root, subRoot)) {
            return true;
        }

        if (isSubtree(root.left, subRoot)) {
            return true;
        }

        if (isSubtree(root.right, subRoot)) {
            return true;
        }

        return false;
    }

    /**
     * 翻转二叉树
     *
     * @param root
     * @return
     */
    public TreeNode invertTree(TreeNode root) {
        if (root == null) {
            return null;
        }

        TreeNode tmp = root.left;
        root.left = root.right;
        root.right = tmp;

        invertTree(root.left);
        invertTree(root.right);

        return root;
    }

    /**
     * 判断二叉树是否为平衡二叉树
     * 平衡二叉树：二叉树的每棵子树的高度差都不超过1
     * 时间复杂度为：O(n)
     *
     * @param root
     * @return
     */
    public boolean isBalanced(TreeNode root) {
        if (root == null) {
            return true;
        }

        return maxDepth(root) >= 0;
    }

    public int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }

        int leftHeight = maxDepth(root.left);
        if (leftHeight < 0) {
            return -1;
        }

        int rightHeight = maxDepth(root.right);

        if (leftHeight >= 0 && rightHeight >= 0
                && Math.abs(leftHeight - rightHeight) <= 1) {
            return Math.max(leftHeight, rightHeight) + 1;
        } else {
            return -1;
        }
    }

    public boolean isSymmetric(TreeNode root) {
        if (root == null) return true;

        return isSymmetricchile(root.left, root.right);
    }

    public boolean isSymmetricchile(TreeNode leftTree, TreeNode rightTree) {
        if (leftTree == null && rightTree != null || leftTree != null && rightTree == null) {
            return false;
        }

        if (leftTree == null && rightTree == null) {
            return true;
        }

        if (leftTree.val != rightTree.val) {
            return false;
        }

        return isSymmetricchile(leftTree.left, rightTree.right)
                && isSymmetricchile(leftTree.right, rightTree.left);
    }

    //层序遍历
    public void levelOrder(TreeNode root) {
        if (root == null) return;

        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        while (!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            System.out.print(cur.val + " ");
            if (cur.left != null) {
                queue.offer(cur.left);
            }
            if (cur.right != null) {
                queue.offer(cur.right);
            }
        }
    }

    /**
     * 二叉树的分层遍历
     */
//    public List<List<Integer>> levelOrder2(TreeNode root) {
//        List<List<Integer>> ret = new ArrayList<>();
//
//        if (root == null) {
//            return ret;
//        }
//
//        Queue<TreeNode> queue = new LinkedList<>();
//        queue.offer(root);
//
//        while (!queue.isEmpty()) {
//            List<Integer> tmpList = new ArrayList<>();
//            int size = queue.size();
//            while (size != 0) {
//                TreeNode cur = queue.poll();
//                size--;
//                tmpList.add(cur.val);
//
//                if (cur.left != null) {
//                    queue.offer(cur.left);
//                }
//                if (cur.right != null) {
//                    queue.offer(cur.right);
//                }
//            }
//            ret.add(tmpList);
//        }
//        return ret;
//    }

    /**
     * 判断是否为完全二叉树
     *
     * @param root
     * @return
     */
    public boolean isCompleteTree(TreeNode root) {
        if (root == null) return true;//假设二叉树为空时是完全二叉树
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        while (!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            if (cur != null) {
                queue.offer(cur.left);
                queue.offer(cur.right);
            } else {
                break;//跳出循环
            }
        }

        while (!queue.isEmpty()) {
            TreeNode cur = queue.peek();
            if (cur == null) {
                queue.poll();
            } else {
                return false;
            }
        }
        return true;
    }

    //找出二叉树两个节点的最近公共祖先
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null) return root;
        if (root == p || root == q) return root;
        TreeNode leftTree = lowestCommonAncestor(root.left, p, q);
        TreeNode rightTree = lowestCommonAncestor(root.right, p, q);
        if (leftTree != null && rightTree != null) {
            return root;
        }else if (leftTree != null) {
            return leftTree;
        }else {
            return rightTree;
        }
    }

    public TreeNode lowestCommonAncestor2(TreeNode root, TreeNode p, TreeNode q) {
        Stack<TreeNode> stackP = new Stack<>();
        Stack<TreeNode> stackQ = new Stack<>();
        getPath(root, p, stackP);
        getPath(root, q, stackQ);

        int sizeP = stackP.size();
        int sizeQ = stackQ.size();
        if (sizeP > sizeQ) {
            int size = sizeP - sizeQ;
            while (size != 0) {
                stackP.pop();
                size--;
            }
        }else {
            int size = sizeQ - sizeP;
            while (size != 0) {
                stackQ.pop();
                size--;
            }
        }

        while (!stackP.isEmpty() && !stackQ.isEmpty()) {
            TreeNode val1 = stackP.pop();
            TreeNode val2 = stackQ.pop();
            if (val1 == val2) {
                return val1;
            }
        }
        return null;
    }

    //将指定路径上的所有节点放入栈中
    private boolean getPath(TreeNode root, TreeNode node, Stack<TreeNode> stack) {
        if (root == null) return false;

        stack.push(root);//将非空节点放入栈中
        if (root == node) return true;

        boolean flg = getPath(root.left, node, stack);
        if (flg) return true;

        flg = getPath(root.right, node, stack);
        if (flg) return true;

        stack.pop();//若flg == false，弹出节点
        return false;
    }

    //根据一棵树的前序遍历与中序遍历构造二叉树
    public int preIndex = 0;
    public TreeNode buildTree(char[] preorder, char[] inorder) {
        return buildTreeChild(preorder, inorder, 0, inorder.length - 1);
    }

    public TreeNode buildTreeChild(char[] preorder, char[] inorder, int inbegin, int inend) {
        if (inbegin > inend) return null;

        TreeNode root = new TreeNode(preorder[preIndex]);

        int rootIndex = findVal(inorder, inbegin, inend, preorder[preIndex]);

        preIndex++;

        root.left = buildTreeChild(preorder, inorder, inbegin, rootIndex - 1);
        root.right = buildTreeChild(preorder, inorder, rootIndex + 1, inend);

        return root;
    }

    private int findVal(char[] inorder, int inbegin, int inend, char key) {
        for (int i = inbegin; i <= inend; i++) {
            if (inorder[i] == key) {
                return i;
            }
        }

        return -1;
    }

    //根据一棵树的中序遍历与后序遍历构造二叉树
    public int postIndex = 0;
    public TreeNode buildTree2(char[] inorder, char[] postorder) {
        postIndex = postorder.length - 1;
        return buildTreeChild(postorder, inorder, 0, inorder.length - 1);
    }

    public TreeNode buildTreeChild2(char[] postorder, char[] inorder, int inbegin, int inend) {
        if (inbegin > inend) return null;

        TreeNode root = new TreeNode(postorder[postIndex]);

        int rootIndex = findVal(inorder, inbegin, inend, postorder[postIndex]);

        postIndex++;

        root.right = buildTreeChild(postorder, inorder, rootIndex + 1, inend);
        root.left = buildTreeChild(postorder, inorder, inbegin, rootIndex - 1);

        return root;
    }

    private int findVal2(char[] inorder, int inbegin, int inend, char key) {
        for (int i = inbegin; i <= inend; i++) {
            if (inorder[i] == key) {
                return i;
            }
        }

        return -1;
    }


    //根据二叉树创建字符串
    public String tree2str(TreeNode root) {
        StringBuilder stringBuilder = new StringBuilder();
        tree2strChild(root, stringBuilder);
        return stringBuilder.toString();
    }

    public void tree2strChild(TreeNode root, StringBuilder stringBuilder) {
        if (root == null) return;
        stringBuilder.append(root.val);

        //左子树
        if (root.left != null) {
            stringBuilder.append("(");
            tree2strChild(root.left, stringBuilder);
            stringBuilder.append(")");
        }else {
            if (root.right == null) {
                return;
            } else {
                stringBuilder.append("()");
            }
        }

        //右子树
        if (root.right != null) {
            stringBuilder.append("(");
            tree2strChild(root.right, stringBuilder);
            stringBuilder.append(")");
        }else {
            return;
        }
    }

    //二叉树的非递归前序遍历
    public List<Character> preorderTraversal(TreeNode root) {
        List<Character> ret = new ArrayList<>();
        if (root == null) return ret;

        Stack<TreeNode> stack = new Stack<>();

        TreeNode cur = root;
        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                System.out.print(cur.val + " ");
                ret.add(cur.val);
                cur = cur.left;
            }
            TreeNode top = stack.pop();
            cur = top.right;
        }
        return ret;
    }

    //二叉树的非递归中序遍历
    public List<Character> inorderTraversal(TreeNode root) {
        List<Character> ret = new ArrayList<>();
        if (root == null) return ret;

        Stack<TreeNode> stack = new Stack<>();

        TreeNode cur = root;
        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            TreeNode top = stack.pop();
            System.out.print(top.val + " ");
            ret.add(top.val);
            cur = top.right;
        }
        return ret;
    }
}